package com.cskaoyan.login;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.*;

/**
 * 创建日期: 2022/03/22 11:18
 *
 * @author ciggar
 *
 * 登录的案例
 */
public class LoginDemo {

    // select * from t_user where username = 'zhangsan' and password = '123456'

    // select * from t_user where username = 'zhangsan' and password = 'xxx' or '1=1'



    // 主方法
    public static void main(String[] args) {
        try {
            // 常规的登录
//            boolean ret = login("zhangsan", "123456");


            // 非常规登录
//            boolean ret = login("asdhajdh", "aefwjfwegb' or '1=1");


            // 常规的登录
//            boolean ret = login2("zhangsan", "123456");


            // 非常规登录
            boolean ret = login2("asdhajdh", "aefwjfwegb' or '1=1");




            if (ret) {
                System.out.println("登录成功！！！");
            }else {
                System.out.println("登录失败！！！");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    // statement登录的方法
    public static boolean login(String username,String password) throws SQLException {

        // 获取连接
        Connection connection = JDBCUtils.getConnection();

        // 获取statement对象
        Statement statement = connection.createStatement();


        String sql = "select * from t_user where username = '" + username + "' and password = '" + password + "'";

        System.out.println(sql);

        // 执行SQL语句
        ResultSet resultSet = statement.executeQuery(sql);

        if (resultSet.next()) {

            return true;
        }
        return false;


    }


    // PrepareStatement 登录的方法
    public static boolean login2(String username,String password) throws SQLException {

        // 获取连接
        Connection connection = JDBCUtils.getConnection();


        // ? 表示占位
        String sql = "select * from t_user where username = ? and password = ?";

        // 这一步会和MySQL服务器进行通信，把SQL语句传递给MySQL服务器
        // MySQL服务器接收到SQL，然后会对SQL语句进行编译
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        // 设值
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);

        // 执行SQL语句
        ResultSet resultSet = preparedStatement.executeQuery();


        if (resultSet.next()) {

            return true;
        }
        return false;


    }


}
